<?php
class StringUtil {
  
  public static function encryptString($string, $key) {
    return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key))));
  }

  public static function decryptString($string, $key) {
    return rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($string), MCRYPT_MODE_CBC, md5(md5($key))), "\0");
  }

  public static function getRandomString($length) {
    $res = '';

    while (strlen($res) < $length) {
      $res .= md5(rand(0, 100000));
    }

    return substr($res, 0, $length);
  }

  public static function getTruncatedString($string, $limit = 80, $appendDots = true) {
    $len = strlen($string);

    if ($len > $limit) {
      $string = substr($string, 0, $limit);

      if ($appendDots)
        $string .= '...';
    }

    return $string;
  }

  public static function nl2html($string) {
    $str = str_replace("\n", '<br />', $string);
    $str = str_replace("\r", '', $str);

    return $str;
  }

  public static function left($string, $left = 0) {
    $len = strlen($string);
    if ($len > $left) {
      $string = substr($string, 0, $left);
    }
    return $string;
  }

  public static function right($string, $right = 0) {
    $len = strlen($string);
    if ($len > $right) {
      $string = substr($string, $len - $right, $right);
    }
    return $string;
  }

  public static function sanitizeFileName($string) {
    $string = strtr($string, 'ŠŽšžŸÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÑÒÓÔÕÖØÙÚÛÜÝàáâãäåçèéêëìíîïñòóôõöøùúûüýÿ', 'SZszYAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy');
    $string = strtr($string, array('Þ' => 'TH', 'þ' => 'th', 'Ð' => 'DH', 'ð' => 'dh', 'ß' => 'ss', 'Œ' => 'OE', 'œ' => 'oe', 'Æ' => 'AE', 'æ' => 'ae', 'µ' => 'u'));
    $string = preg_replace(array('/\s/', '/\.[\.]+/', '/[^\w_\.\-]/'), array('_', '.', ''), $string);

    return $string;
  }
  
  public static function stripSpecialChars($string) {
    return preg_replace('/[^a-zA-Z0-9]/', '', $string);
  }
}